package com.vae.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vae.cart.model.Cart;
import com.vae.goods.mapper.AdItemsMapper;
import com.vae.goods.mapper.SkuMapper;
import com.vae.goods.service.SkuService;
import com.vae.mall.goods.api.aggregate.AditemSku;
import com.vae.mall.goods.api.entity.AdItems;
import com.vae.mall.goods.api.entity.Sku;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Sku 服务实现类
 * @author  vae
 * @since 1.0
 */
@Service
public class SkuServiceImpl extends ServiceImpl<SkuMapper, Sku> implements SkuService {

    @Autowired
    private AdItemsMapper adItemsMapper;

    @Autowired
    private SkuMapper skuMapper;

    /***
     * 根据推广产品分类ID查询Sku列表
     * @param id
     * @return
     */
    @Override
    public List<AditemSku> typeSkuItems(Integer id) {
        return queryAditemSkuByTypeId(id);
    }
    /****
     * 清理分类ID下的推广产品
     * @param id
     */
    @CacheEvict(cacheNames = "ad-items-skus",key ="#id")
    @Override
    public void delTypeSkuItems(Integer id) {
        //TODO 暂时没做数据库删除操作，只删除了缓存，后续可以添加
    }


    /**
     * 缓存修改
     * @param id
     * @return
     */
    @CachePut(cacheNames = "ad-items-skus",key = "#id")
    @Override
    public List<AditemSku> updateTypeItems(Integer id) {
        //TODO 正常流程应该是修改数据库后修改缓存，这里只是通过再查一遍数据库后，修改缓存，后续可以进行补充
        return queryAditemSkuByTypeId(id);
    }


    //根据分类ID查询分类下的推广产品
    private List<AditemSku> queryAditemSkuByTypeId(Integer id) {

        //查询所有分类下的推广
        QueryWrapper<AdItems> adItemsQueryWrapper=new QueryWrapper<AdItems>();
        adItemsQueryWrapper.eq("type",id);

        // 查询所有推广项
        List<AdItems> adItems = adItemsMapper.selectList(adItemsQueryWrapper);

        // 根据专区名称分组，并收集sku_id
        Map<String, List<String>> aditemGroups = adItems.stream()
                .collect(Collectors.groupingBy(AdItems::getName, Collectors.mapping(AdItems::getSkuId, Collectors.toList())));

        // 创建一个空的List<AditemSku>
        List<AditemSku> aditemSkus = new ArrayList<>();

        // 遍历分组，查询每个分组对应的Sku信息，并创建AditemSku对象
        for (Map.Entry<String, List<String>> entry : aditemGroups.entrySet()) {
            String aditemName = entry.getKey();
            List<String> skuIds = entry.getValue();

            // 批量查询Sku
            List<Sku> skus = skuMapper.selectBatchIds(skuIds);

            // 创建AditemSku对象并添加到列表中
            AditemSku aditemSku = new AditemSku(aditemName, skus);
            aditemSkus.add(aditemSku);
        }
        return aditemSkus;
    }


    /***
     * 库存递减
     * @param carts
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void decount(List<Cart> carts) {
        for (Cart cart : carts) {
            //语句级控制，防止超卖
            int count = skuMapper.decount(cart.getSkuId(),cart.getNum());
            if(count<=0){
                throw new RuntimeException("库存不足！");
            }
        }
    }


}